package com.hst.web.base.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.hst.core.ServiceContext;
import com.hst.core.dao.IORDao;
import com.hst.core.dao.ISQLDao;
import com.hst.core.dao.ORQuery;
import com.hst.core.dao.ORQuery.Op;
import com.hst.core.json.JsonUtil;
import com.hst.web.auth.po.User;
import com.hst.web.common.utils.ConstantUtil;
import com.hst.web.sys.entity.TUserContractor;
import com.hst.web.sys.entity.TUserDept;

@Controller
@RequestMapping("/sumtable")
public class SumTableController {

	@Autowired
	ISQLDao sql;

	@Autowired
	IORDao dao;

	@SuppressWarnings({ "unchecked", "unused" })
	@RequestMapping("/query")
	public void query(@RequestBody String data, Model m) throws JsonParseException, JsonMappingException, IOException {
		Map<String, Object> param = JsonUtil.read(data, Map.class);
		String s = (String) param.get("name");
		int pageIdx = param.get("pageIdx") != null ? (int) param.get("pageIdx") : 1;
		int pageSize = param.get("pageSize") != null ? (int) param.get("pageSize") : 20;
		List<ORQuery> querys = new ArrayList<ORQuery>();

		User u = (User) ServiceContext.getInstance().getUser();
		// 部门管理员
		if (u.getPrivileges().contains(ConstantUtil.DEPT_MANAGER_PRIVLIGE)) {
			List<String> deptList = new ArrayList<String>();
			deptList.add("");
			for (TUserDept d : dao.list(TUserDept.class, new ORQuery(Op.eq, "userid", u.getId())))
				deptList.add(d.getDeptCode());
			param.put("deptCode", deptList);
		}
		String companyCode = u.getCompanyCode();
		String contractorCode = u.getContractorCode();
		if (!StringUtils.isEmpty(companyCode))
			param.put("companyCode", companyCode);

		querys.add(new ORQuery(Op.eq, "companyCode", companyCode));
		querys.add(new ORQuery(Op.eq, "userid", u.getId()));

		// 承包商管理员
		if ("1".equals(u.getUserType())) {	
			List<String> list = new ArrayList<String>();
			list.add("");
			for (TUserContractor e : dao.list(TUserContractor.class, querys)) {
				list.add(e.getContractorCode());
			}
			param.put("contractorCode", list);
		}
		m.addAttribute("data", sql.list("sumtable." + s, param, pageIdx, pageSize));
	}
	
}
